package com.irdstudio.apicenter.frame.core.jdbc.tablemodel;

import org.springframework.jdbc.core.support.JdbcDaoSupport;

import com.irdstudio.apicenter.frame.core.jdbc.JdbcDBException;
import com.irdstudio.apicenter.frame.core.jdbc.container.DataList;
import com.irdstudio.apicenter.frame.core.jdbc.container.PageInfo;

/**
 * 基于ORACLE表模型基本操作的DAO
 * 
 * @author zs.ligm
 * @version 1.0
 * @date 2015-07-20
 */
public class TableModelDao4Oracle extends JdbcDaoSupport implements
		ITableModelDAO {

	/**
	 * 实现Oracle下分页查询
	 */
	@Override
	public DataList queryList(String sql, PageInfo pageInfo, Object[] params)
			throws JdbcDBException {

		StringBuffer totalSql = new StringBuffer("select count(1) from (")
				.append(sql).append(") t");
		pageInfo.setRecordSize(this.getJdbcTemplate().queryForInt(
				totalSql.toString(), params));

		// 计算分页信息
		pageInfo.beginIdx = (pageInfo.pageIdx - 1) * pageInfo.pageSize + 1;
		pageInfo.endIdx = pageInfo.beginIdx + pageInfo.pageSize - 1;

		// 组装分页查询语句
		StringBuffer pageSql = new StringBuffer();
		pageSql.append("SELECT * FROM ( SELECT rownum row_num, t.*  FROM (");
		pageSql.append(sql).append(" ) t ) ");
		pageSql.append(" WHERE row_num BETWEEN ").append(pageInfo.beginIdx);
		pageSql.append(" AND ").append(pageInfo.endIdx);

		// 获得分页数据并返回
		return new DataList(this.getJdbcTemplate().queryForList(
				pageSql.toString(), params));
	}

	@Override
	public String getNativePageSql(String sql, int beginIdx, int pageSize) {
		// 组装分页查询语句
		StringBuffer pageSql = new StringBuffer();
		pageSql.append("SELECT * FROM ( SELECT rownum row_num, t.*  FROM (");
		pageSql.append(sql).append(" ) t ) ");
		pageSql.append(" WHERE row_num BETWEEN ").append(beginIdx);
		pageSql.append(" AND ").append((beginIdx + pageSize));
		return pageSql.toString();
	}

}
